package org.jeecg.modules.flower.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.flower.entity.*;
import org.jeecg.modules.flower.service.IFlowerPlantingBaseService;
import org.jeecg.modules.flower.service.IFlowerPlantingGreenhouseService;
import org.jeecg.modules.flower.service.IFlowerTagpreService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.system.entity.SysUser;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 预出库台账
 * @Author: jeecg-boot
 * @Date:   2022-06-24
 * @Version: V1.0
 */
@Api(tags="预出库台账")
@RestController
@RequestMapping("/flower/flowerTagpre")
@Slf4j
public class FlowerTagpreController extends JeecgController<FlowerTagpre, IFlowerTagpreService> {
	@Autowired
	private IFlowerTagpreService flowerTagpreService;

	 @Autowired
	 private IFlowerPlantingBaseService flowerPlantingBaseService;

	 @Autowired
	 private IFlowerPlantingGreenhouseService flowerPlantingGreenhouseService;

	 /**
	 * 分页列表查询
	 *
	 * @param flowerTagpre
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "预出库台账-分页列表查询")
	@ApiOperation(value="预出库台账-分页列表查询", notes="预出库台账-分页列表查询")
	@GetMapping(value = "/list")
	@PermissionData(pageComponent = "flower/FlowerTagpreList")
	public Result<?> queryPageList(FlowerTagpre flowerTagpre,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   @RequestParam(value = "sDate",defaultValue = "") String sDate ,
								   @RequestParam(value = "eDate",defaultValue = "") String eDate,
								   HttpServletRequest req) {
//		QueryWrapper<FlowerTagpre> queryWrapper = QueryGenerator.initQueryWrapper(flowerTagpre, req.getParameterMap());
		QueryWrapper<FlowerTagpre> queryWrapper = new QueryWrapper<>();
		Page<FlowerTagpre> page = new Page<FlowerTagpre>(pageNo, pageSize);
		if (StringUtils.isNotBlank(flowerTagpre.getSourceBase())) {
			queryWrapper.like("source_base", flowerTagpre.getSourceBase());
		}
		if (StringUtils.isNotBlank(flowerTagpre.getSourceGreenhouse())) {
			queryWrapper.eq("source_greenhouse", flowerTagpre.getSourceGreenhouse());
		}
		if(StringUtils.isNotBlank(sDate)){
			queryWrapper.ge("stock_in_time",sDate);
		}
		if(StringUtils.isNotBlank(eDate)){
			queryWrapper.le("stock_in_time",eDate);
		}
		if(StringUtils.isNotBlank(flowerTagpre.getChannel())){
			queryWrapper.eq("channel", flowerTagpre.getChannel()) ;
		}
		if(StringUtils.isNotBlank(flowerTagpre.getAccountno())){
			queryWrapper.eq("accountno", flowerTagpre.getAccountno()) ;
		}
		if(StringUtils.isNotBlank(flowerTagpre.getStorehouse())){
			queryWrapper.eq("storehouse", flowerTagpre.getStorehouse()) ;
		}
		if(StringUtils.isNotBlank(flowerTagpre.getCost())){
			queryWrapper.eq("cost", flowerTagpre.getCost()) ;
		}
		if(StringUtils.isNotBlank(flowerTagpre.getVariety())){
			queryWrapper.like("variety", flowerTagpre.getVariety()) ;
		}
		if(StringUtils.isNotBlank(flowerTagpre.getVarietyCode())){
			queryWrapper.like("variety_code", flowerTagpre.getVarietyCode()) ;
		}
		if(StringUtils.isNotBlank(flowerTagpre.getPackingSpecifications())){
			queryWrapper.eq("packing_specifications", flowerTagpre.getPackingSpecifications()) ;
		}
		if(StringUtils.isNotBlank(flowerTagpre.getFlowerPoleLength())){
			queryWrapper.eq("flower_pole_length", flowerTagpre.getFlowerPoleLength()) ;
		}

		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
		queryWrapper.inSql("storehouse","select b.code from flower_storehouse b , flower_storehouse_detail c where b.id = c.mainid  and c.personid = '"+sysUser.getId()+"'");
//		queryWrapper.exists("select 1 from flower_storehouse b , flower_storehouse_detail c where b.id = c.mainid and b.code=storehouse  and c.personid = '"+sysUser.getId()+"'");
		QueryGenerator.installAuthMplus(queryWrapper,FlowerTagpre.class);
		IPage<FlowerTagpre> pageList = flowerTagpreService.page(page, queryWrapper);

		List<FlowerTagpre> records = pageList.getRecords();
		for (FlowerTagpre record : records) {
			FlowerPlantingBase base = flowerPlantingBaseService.getById(record.getSourceBase());
			if (base != null) {
				record.setSourceBase(base.getName());
			}
			FlowerPlantingGreenhouse greenhouse = flowerPlantingGreenhouseService.getById(record.getSourceGreenhouse());
			if (greenhouse != null) {
				record.setSourceGreenhouse(greenhouse.getName());
			}
		}

		return Result.ok(pageList);
	}




	 /**
	 * --台账列表-
	 *
	 * @param flowerTagpre
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "预出库台账--台账列表-分页列表查询")
	@ApiOperation(value="预出库台账--台账列表--分页列表查询", notes="预出库台账-分页列表查询")
	@GetMapping(value = "/list2")
	@PermissionData(pageComponent = "flower/FlowerTagpreList")
	public Result<?> queryPageList2(FlowerTagpre flowerTagpre,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {

		QueryWrapper<FlowerTagpre> queryWrapper = new QueryWrapper<>();
		if (StringUtils.isNotBlank(flowerTagpre.getSourceBase())) {
			queryWrapper.like("source_base", flowerTagpre.getSourceBase());
		}
		if (StringUtils.isNotBlank(flowerTagpre.getSourceGreenhouse())) {
			queryWrapper.eq("source_greenhouse", flowerTagpre.getSourceGreenhouse());
		}
		if(StringUtils.isNotBlank(flowerTagpre.getChannel())){
			queryWrapper.eq("channel", flowerTagpre.getChannel()) ;
		}
		if(StringUtils.isNotBlank(flowerTagpre.getAccountno())){
			queryWrapper.eq("accountno", flowerTagpre.getAccountno()) ;
		}
		if(StringUtils.isNotBlank(flowerTagpre.getStorehouse())){
			queryWrapper.like("storehouse", flowerTagpre.getStorehouse()) ;
		}
		if(StringUtils.isNotBlank(flowerTagpre.getCost())){
			queryWrapper.like("cost", flowerTagpre.getCost()) ;
		}
		if(StringUtils.isNotBlank(flowerTagpre.getVariety())){
			queryWrapper.like("variety", flowerTagpre.getVariety()) ;
		}
		if(StringUtils.isNotBlank(flowerTagpre.getVarietyCode())){
			queryWrapper.like("variety_code", flowerTagpre.getVarietyCode()) ;
		}
		if(StringUtils.isNotBlank(flowerTagpre.getPackingSpecifications())){
			queryWrapper.like("packing_specifications", flowerTagpre.getPackingSpecifications()) ;
		}
		if(StringUtils.isNotBlank(flowerTagpre.getFlowerPoleLength())){
			queryWrapper.like("flower_pole_length", flowerTagpre.getFlowerPoleLength()) ;
		}
		if(StringUtils.isNotBlank(flowerTagpre.getCreateUser())){
			queryWrapper.eq("create_user", flowerTagpre.getCreateUser()) ;
		}
		if(flowerTagpre.getState()==null){
			queryWrapper.eq("state",1);
		}
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
		//如果是业务员，只能查看自己的数据，其他职务可以看全部。2022年12月2日17:01:52
//		String post = sysUser.getPost();
//		if(StringUtils.isBlank(post) || "businessPerson".equals(post)){
//			queryWrapper.eq("create_user", sysUser.getUsername()) ;
//		}
		
		Page<FlowerTagpre> page = new Page<FlowerTagpre>(pageNo, pageSize);

		
		queryWrapper.select("source_base , source_greenhouse ,storehouse, channel ,accountno, cost, variety,variety_code,packing_specifications,flower_pole_length,classes , count(1) as num ");
		queryWrapper.inSql("storehouse","select b.code from flower_storehouse b , flower_storehouse_detail c where b.id = c.mainid and c.personid = '"+sysUser.getId()+"'");
//		queryWrapper.exists("select 1 from flower_storehouse b , flower_storehouse_detail c where b.id = c.mainid and b.code=storehouse  and c.personid = '"+sysUser.getId()+"'");
		queryWrapper.groupBy("source_base", "source_greenhouse" ,"storehouse", "channel" ,"accountno","cost", "variety","variety_code","packing_specifications","flower_pole_length,classes");
		queryWrapper.orderByDesc("num");
		QueryGenerator.installAuthMplus(queryWrapper,FlowerTagpre.class);
		IPage<FlowerTagpre> pageList = flowerTagpreService.page(page, queryWrapper);

		return Result.ok(pageList);
	}

	/**
	 * --台账列表-   单独授权--用于销售确认  台创选择
	 *
	 * @param flowerTagpre
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "预出库台账--台账列表-分页列表查询")
	@ApiOperation(value="预出库台账--台账列表--分页列表查询", notes="预出库台账-分页列表查询")
	@GetMapping(value = "/list3")
	@PermissionData(pageComponent = "flower/FlowerPreList")
	public Result<?> queryPageList3(FlowerTagpre flowerTagpre,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {

		QueryWrapper<FlowerTagpre> queryWrapper = new QueryWrapper<>();
		if (StringUtils.isNotBlank(flowerTagpre.getSourceBase())) {
			queryWrapper.like("source_base", flowerTagpre.getSourceBase());
		}
		if (StringUtils.isNotBlank(flowerTagpre.getSourceGreenhouse())) {
			queryWrapper.eq("source_greenhouse", flowerTagpre.getSourceGreenhouse());
		}
		if(StringUtils.isNotBlank(flowerTagpre.getChannel())){
			queryWrapper.eq("channel", flowerTagpre.getChannel()) ;
		}
		if(StringUtils.isNotBlank(flowerTagpre.getAccountno())){
			queryWrapper.eq("accountno", flowerTagpre.getAccountno()) ;
		}
		if(StringUtils.isNotBlank(flowerTagpre.getStorehouse())){
			queryWrapper.like("storehouse", flowerTagpre.getStorehouse()) ;
		}
		if(StringUtils.isNotBlank(flowerTagpre.getCost())){
			queryWrapper.like("cost", flowerTagpre.getCost()) ;
		}
		if(StringUtils.isNotBlank(flowerTagpre.getVariety())){
			queryWrapper.like("variety", flowerTagpre.getVariety()) ;
		}
		if(StringUtils.isNotBlank(flowerTagpre.getVarietyCode())){
			queryWrapper.like("variety_code", flowerTagpre.getVarietyCode()) ;
		}
		if(StringUtils.isNotBlank(flowerTagpre.getPackingSpecifications())){
			queryWrapper.like("packing_specifications", flowerTagpre.getPackingSpecifications()) ;
		}
		if(StringUtils.isNotBlank(flowerTagpre.getFlowerPoleLength())){
			queryWrapper.like("flower_pole_length", flowerTagpre.getFlowerPoleLength()) ;
		}
		if(StringUtils.isNotBlank(flowerTagpre.getCreateUser())){
			queryWrapper.eq("create_user", flowerTagpre.getCreateUser()) ;
		}
		if(flowerTagpre.getState()==null){
			queryWrapper.eq("state",1);
		}
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
		//如果是业务员，只能查看自己的数据，其他职务可以看全部。2022年12月2日17:01:52
//		String post = sysUser.getPost();
//		if(StringUtils.isBlank(post) || "businessPerson".equals(post)){
//			queryWrapper.eq("create_user", sysUser.getUsername()) ;
//		}

		Page<FlowerTagpre> page = new Page<FlowerTagpre>(pageNo, pageSize);


		queryWrapper.select("source_base , source_greenhouse ,storehouse, channel ,accountno, cost, variety,variety_code,packing_specifications,flower_pole_length,classes , count(1) as num ");
		queryWrapper.inSql("storehouse","select b.code from flower_storehouse b , flower_storehouse_detail c where b.id = c.mainid and c.personid = '"+sysUser.getId()+"'");
//		queryWrapper.exists("select 1 from flower_storehouse b , flower_storehouse_detail c where b.id = c.mainid and b.code=storehouse  and c.personid = '"+sysUser.getId()+"'");
		queryWrapper.groupBy("source_base", "source_greenhouse" ,"storehouse", "channel" ,"accountno","cost", "variety","variety_code","packing_specifications","flower_pole_length,classes");
		queryWrapper.orderByDesc("num");
		QueryGenerator.installAuthMplus(queryWrapper,FlowerTagpre.class);
		IPage<FlowerTagpre> pageList = flowerTagpreService.page(page, queryWrapper);

		return Result.ok(pageList);
	}

	/**
	 *   添加
	 *
	 * @param flowerTagpre
	 * @return
	 */
	@AutoLog(value = "预出库台账-添加")
	@ApiOperation(value="预出库台账-添加", notes="预出库台账-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody FlowerTagpre flowerTagpre) {

		flowerTagpreService.save(flowerTagpre);
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param flowerTagpre
	 * @return
	 */
	@AutoLog(value = "预出库台账-编辑")
	@ApiOperation(value="预出库台账-编辑", notes="预出库台账-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody FlowerTagpre flowerTagpre) {
		flowerTagpreService.updateById(flowerTagpre);
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "预出库台账-通过id删除")
	@ApiOperation(value="预出库台账-通过id删除", notes="预出库台账-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		flowerTagpreService.removeById(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "预出库台账-批量删除")
	@ApiOperation(value="预出库台账-批量删除", notes="预出库台账-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.flowerTagpreService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "预出库台账-通过id查询")
	@ApiOperation(value="预出库台账-通过id查询", notes="预出库台账-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		FlowerTagpre flowerTagpre = flowerTagpreService.getById(id);
		if(flowerTagpre==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(flowerTagpre);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param flowerTagpre
    */
    @RequestMapping(value = "/exportXls")
	@PermissionData(pageComponent = "flower/FlowerTagpreList")
    public ModelAndView exportXls(HttpServletRequest request, FlowerTagpre flowerTagpre) {
        return super.exportXls(request, flowerTagpre, FlowerTagpre.class, "预出库台账");
    }
	 /**
	  * 导出excel
	  *
	  * @param request
	  * @param flowerTagpre
	  */
	 @RequestMapping(value = "/exportXls2")
	 @PermissionData(pageComponent = "flower/FlowerTagpreList")
	 public ModelAndView exportXlsAll(HttpServletRequest request, FlowerTagpre flowerTagpre,
									@RequestParam(value = "sDate",defaultValue = "") String sDate ,
									@RequestParam(value = "eDate",defaultValue = "") String eDate) {
		 QueryWrapper<FlowerTagpre> queryWrapper = new QueryWrapper<>();
		 if(StringUtils.isNotBlank(flowerTagpre.getChannel())){
			 queryWrapper.eq("channel", flowerTagpre.getChannel()) ;
		 }
		 if(StringUtils.isNotBlank(flowerTagpre.getAccountno())){
			 queryWrapper.eq("accountno", flowerTagpre.getAccountno()) ;
		 }
		 if(StringUtils.isNotBlank(flowerTagpre.getStorehouse())){
			 queryWrapper.like("storehouse", flowerTagpre.getStorehouse()) ;
		 }
		 if(StringUtils.isNotBlank(flowerTagpre.getCost())){
			 queryWrapper.like("cost", flowerTagpre.getCost()) ;
		 }
		 if(StringUtils.isNotBlank(flowerTagpre.getVariety())){
			 queryWrapper.like("variety", flowerTagpre.getVariety()) ;
		 }
		 if(StringUtils.isNotBlank(flowerTagpre.getVarietyCode())){
			 queryWrapper.like("variety_code", flowerTagpre.getVarietyCode()) ;
		 }
		 if(StringUtils.isNotBlank(flowerTagpre.getPackingSpecifications())){
			 queryWrapper.like("packing_specifications", flowerTagpre.getPackingSpecifications()) ;
		 }
		 if(StringUtils.isNotBlank(flowerTagpre.getFlowerPoleLength())){
			 queryWrapper.like("flower_pole_length", flowerTagpre.getFlowerPoleLength()) ;
		 }
		 if(flowerTagpre.getState()==null){
			 queryWrapper.eq("state",1);
		 }

		 if(StringUtils.isNotBlank(sDate)){
			 queryWrapper.ge("stock_in_time",sDate);
		 }
		 if(StringUtils.isNotBlank(eDate)){
			 queryWrapper.le("stock_in_time",eDate+" 23:59:59");
		 }

		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
		 queryWrapper.select("source_base , source_greenhouse ,storehouse, channel ,accountno, cost, variety,variety_code,packing_specifications,flower_pole_length, count(1) as classes ");
		 queryWrapper.inSql("storehouse","select b.code from flower_storehouse b , flower_storehouse_detail c where b.id = c.mainid and c.personid = '"+sysUser.getId()+"'");
//		 queryWrapper.exists("select 1 from flower_storehouse b , flower_storehouse_detail c where b.id = c.mainid and b.code=storehouse  and c.personid = '"+sysUser.getId()+"'");
		 queryWrapper.groupBy("source_base" , "source_greenhouse" ,"storehouse", "channel" ,"accountno","cost", "variety","variety_code","packing_specifications","flower_pole_length");
		 queryWrapper.orderByDesc("classes");

		 QueryGenerator.installAuthMplus(queryWrapper,FlowerTagpre.class);
		 List<FlowerTagpre> pageList = flowerTagpreService.list( queryWrapper);
		 ArrayList<FlowerTagpreForExport> list  =new ArrayList<>();
		 for( FlowerTagpre  ll  :pageList){
			 FlowerTagpreForExport flowerTagpreForExport =new FlowerTagpreForExport();
			 BeanUtils.copyProperties(ll, flowerTagpreForExport);
			 list.add(flowerTagpreForExport);
		 }
		 String title ="预出库台账";
		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 mv.addObject(NormalExcelConstants.FILE_NAME, title); //此处设置的filename无效 ,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.CLASS, FlowerTagpreForExport.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title));
		 mv.addObject(NormalExcelConstants.DATA_LIST, list);
		 return mv;
	 }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, FlowerTagpre.class);
    }

}
